import storage from '@/utils/storage'
import { TABS_ROUTES } from '@/store/constantKeys'

// 不需要在标签页中出现的路由
const hiddenTabs = ['Redirect', 'Login']

const state = {
  tabs: storage.get(TABS_ROUTES, [])
}

const mutations = {
  // 初始化标签页
  initTabs: (state, routes) => {
    state.tabs = routes
  },
  // 添加标签页
  addTabs: (state, route) => {
    if (hiddenTabs.includes(route.name)) return false

    // 确保hidden(大多数都是详情页)的路由只能打开一个
    if (route.meta && route.meta.hidden) {
      let index = -1
      for (let i = 0, length = state.tabs.length; i < length; i++) {
        const sub = state.tabs[i]
        if (sub.path === route.path) {
          index = i
          break
        }
      }
      if (index !== -1) {
        state.tabs.push(route)
      }
    } else {
      const isExists = state.tabs.some(el => el.fullPath === route.fullPath)
      if (!isExists) state.tabs.push(route)
    }

    return true
  },
  // 关闭左侧
  closeLeftTabs: (state, route) => {
    const index = state.tabs.findIndex(el => el.fullPath === route.fullPath)
    state.tabs.splice(0, index)
  },
  // 关闭右侧
  closeRightTabs: (state, route) => {
    const index = state.tabs.findIndex(el => el.fullPath === route.fullPath)
    state.tabs.splice(index + 1)
  },
  // 关闭其他
  closeOtherTabs: (state, route) => {
    state.tabs = state.tabs.filter(el => el.fullPath === route.fullPath)
  },
  // 关闭当前页
  closeCurrentTabs: (state, route) => {
    const index = state.tabs.findIndex(el => el.fullPath === route.fullPath)
    state.tabs.splice(index, 1)
  }
}

const getters = {
  tabs: (state) => state.tabs
}

export default {
  namespaced: true,
  state,
  mutations,
  getters
}
